﻿using System.IO;
using Microsoft.Win32;

namespace Oxage.CNC.Models
{
	public partial class DocumentViewModel : DocumentModel
	{
		#region Public properties
		public string LastUsedFileName
		{
			get
			{
				return this.lastUsedFileName;
			}
			set
			{
				if (this.lastUsedFileName != value)
				{
					this.lastUsedFileName = value;
					OnPropertyChanged("LastUsedFileName");
					OnPropertyChanged("CanSaveWithoutDialog");
				}
			}
		}
		private string lastUsedFileName;

		/// <summary>
		/// Gets a value indicating whether user can save content directly without opening file dialog.
		/// </summary>
		public bool CanSaveWithoutDialog
		{
			get
			{
				return !string.IsNullOrEmpty(this.LastUsedFileName);
			}
		}
		#endregion

		#region Public methods
		public void New()
		{
			this.Content = "";
			this.LastUsedFileName = null;
		}

		public void OpenDialog()
		{
			var dialog = new OpenFileDialog();
			dialog.Filter = "G code (*.cnc)|*.*";

			if (dialog.ShowDialog() == true)
			{
				this.Content = File.ReadAllText(dialog.FileName);
				this.LastUsedFileName = dialog.FileName;
			}
		}

		public void Save()
		{
			if (this.CanSaveWithoutDialog)
			{
				File.WriteAllText(this.LastUsedFileName, this.Content);
			}
		}

		public void SaveDialog()
		{
			var dialog = new SaveFileDialog();
			dialog.Filter = "G code (*.cnc)|*.*";

			if (dialog.ShowDialog() == true)
			{
				File.WriteAllText(dialog.FileName, this.Content);
				this.LastUsedFileName = dialog.FileName;
			}
		}
		#endregion
	}
}
